# coding: utf-8
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QResizeEvent
from PySide6.QtWidgets import QHBoxLayout
from qfluentwidgets import FluentIcon as FIF, BodyLabel, TransparentToolButton, setFont, StateToolTip

from components import VerticalScrollArea, Alert
from threads import WorkerThread


class PluginBase(VerticalScrollArea):
    NAME = "PluginBase"
    DESCRIPTION = "This is a base class for plugins."
    ICON = FIF.APPLICATION

    closed = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout()
        self.returnBtn = TransparentToolButton(FIF.RETURN, self)
        self.titleLabel = BodyLabel(self.NAME, self)
        self.worker = WorkerThread(self)
        self.toolTip = StateToolTip('加载中', '正在处理...', self)

        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(self.returnBtn)
        self.horizontalLayout.addWidget(self.titleLabel)
        self.addLayout(self.horizontalLayout, 0)

        setFont(self.titleLabel, 20)
        self.returnBtn.setFixedSize(40, 40)

        self.toolTip.close()
        self.returnBtn.clicked.connect(self.closed)
        self.worker.started.connect(self.toolTip.show)
        self.worker.finished.connect(self.toolTip.hide)
        self.worker.failed.connect(lambda msg: Alert.error(f'任务失败: {msg}'))
        self.worker.result.connect(self._onResult)

    def setTitle(self, title: str):
        self.titleLabel.setText(title)

    def load(self, func, *args, slot=None, **kwargs):
        self.worker.addTask(func, *args, slot=slot, **kwargs)

    def resizeEvent(self, event: QResizeEvent):
        self.toolTip.move(self.width() - self.toolTip.width() - 10, 45)
        super().resizeEvent(event)

    def _onResult(self, slot, result):
        if slot:
            slot(result)
